package com.stlm2.dems.dao.impl;

import com.google.gson.Gson;
import com.stlm2.core.common.page.PageView;
import com.stlm2.core.redis.RedisClient;
import com.stlm2.dems.user.dao.LowerDao;
import com.stlm2.dems.user.entity.Lower;
import com.stlm2.dems.user.entity.UserLevel;
import com.stlm2.util.Memcached;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.stereotype.Repository;

import com.stlm2.dems.entity.User;
import com.stlm2.dems.dao.UserDao;
import com.stlm2.core.base.impl.BaseDaoImpl;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository("userDao")
public class UserDaoImpl extends BaseDaoImpl<User> implements UserDao {
    @Override
    public List<User> getByShopId(int shopId) {
        return selectList("getByShopId",shopId);
    }

    @Resource
    private Memcached memcached;
    @Resource
    private LowerDao lowerDao;
    public User getByName(String name){
       return  selectOne("getByName",name);
   }
    public List<User> getByEmail(String email){
       return selectList("getByEmail",email);
    }
    public  User getByToken(String token){
        User user = new User();
        if (token != null && !"".equals(token)) {
            Gson gson = new Gson();
            try {
                user = gson.fromJson(memcached.get(token).toString(), User.class);
            } catch (Exception e) {
                return null;
            }
        }else {
            return null;
        }
        return user;
    }

    @Override
    public void userTokenCheck(String token, Integer userId) {
        String userToken="token:"+userId;
        JedisPool pool = null;
        Jedis jedis = null;
        try {
            pool = RedisClient.getPool();
            jedis = pool.getResource();
            String tokenArr =(String) jedis.get(userToken);
            if(tokenArr!=null) {
                String[] tokenAr = tokenArr.split(":");
                if(tokenAr.length>=3){//已经存入token数大于等于三个
                    //需要删除第三个及以上的token
                    for (int i=2;i<tokenAr.length;i++){
                        memcached.delete(tokenAr[i]);
                    }
                    //最新登陆生成的token放在第一个位置上
                    String tokenArrr=token+":"+tokenAr[0]+":"+tokenAr[1];
                   jedis.set(userToken,tokenArrr);
                }else {//已存入一个或两个token
                    //最新token放在第一个位置上
                    String tokenArrr=token+":"+tokenArr;
                    jedis.set(userToken,tokenArrr);
                }
            }else {
                jedis.set(userToken,token);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            pool.returnResource(jedis);
        }
    }

    @Override
    public void updateUserToken(User user, String token) {
        if(user==null||token==null){
            return;
        }
         modify(user);
        Gson gson = new Gson();
        JedisPool pool = null;
        Jedis jedis = null;
        try {
            pool = RedisClient.getPool();
            jedis = pool.getResource();
            String userToken = "token:" + user.getId();
            String tokenArr = jedis.get(userToken);
            if (tokenArr != null) {
                String[] tokenAr = tokenArr.split(":");
                for(int i=0;i<tokenAr.length;i++){
                    memcached.set(tokenAr[i], 15*24*60*60, gson.toJson(user).toString());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            pool.returnResource(jedis);
        }
    }

    @Override
    public List<User> getByUserName(String name) {
        return selectList("getByUserName",name);
    }


    @Override
    public User getAgentUser(Integer id) {
        return selectOne("getAgentUser",id);
    }

    @Override
    public List<User> getByRoleId(int roleId) {
        return selectList("getByRoleId",roleId);
    }

    @Override
    public List<User> getByUpper() {
        return selectList("getByUpper","");
    }

    @Override
    public Integer userUpperLevel(Integer userId) {
        User user=getById(userId);
        if(user==null){
            return null;
        }
        Integer userLevelValue=user.getUserLevelValue();

        if(userLevelValue==2){
            return null;
        }
        if(userLevelValue==1){
            Integer count=countUserByLevel(userId,userLevelValue);
            if(count>=10000){
                user.setUserLevel(UserLevel.Gold);
                modify(user);
                return userUpperLevel(userId);
            }
            Lower lower=lowerDao.getByLowerUserId(userId);
            if(lower==null){
                return null;
            }else {
                return userUpperLevel(lower.getUserId());
            }
        }else {
            return null;
        }
    }

    @Override
    public Integer countUserByLevel(Integer userId, Integer userLevelValue) {
        Map<String,Object> map=new HashMap<String, Object>();
        map.put("userId",userId);
        map.put("userLevelValue",userLevelValue);
        return  (Integer) _selectOne("countByUserLevel",map);
    }

    @Override
    public User getByLowerUserId(Integer id) {
        return selectOne("getByLowerUserId",id);
    }

    @Override
    public List<User> getUserLevel() {
        return selectList("getByUserLevel","");
    }

    @Override
    public User getByWxOpenID(String wxOpenId) {
        return selectOne("getByWxOpenID",wxOpenId);
    }

    @Override
    public User getByQqOpenID(String qqOpenId) {
        return selectOne("getByQqOpenID",qqOpenId);
    }

    @Override
    public PageView getInitRoleUser(int pageNo, int pageSize, int roleInit) {
        Map<String, Object> params = new HashedMap();
        params.put("roleInit",roleInit);
        return  queryPageView(pageNo,pageSize,"getInitRoleUser",params);
    }
}